package com.smartsofa.main;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.smartsofa.R;
import com.smartsofa.db.SQLHelper;
import com.smartsofa.entity.ChannelItem;
import com.smartsofa.entity.ChannelManage;
import com.smartsofa.recommend.FlowLayout;
import com.smartsofa.recommend.TagAdapter;
import com.smartsofa.recommend.TagFlowLayout;
import com.smartsofa.util.MyUtils;

public class RegisterActivity extends Activity {
	
	private Button bt_back;
	private Button bt_register;
	private EditText et_username;
	private EditText et_password;
	private EditText et_phone;
	private ToggleButton tb_gender;
	private EditText et_deviceId;
	private EditText et_weight;
	private EditText et_height;
	
	private String username;
	private String password;
	private String gender;
	private String phone;
	private String deviceId;
	private String weight;
	private String height;
	private String interestTag=new String();
	
	private String url;
	private Boolean flag=false;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private String reg_msg;
	private ProgressDialog mDialog;	
	Intent intent=new Intent();
	/** 其它栏目列表 */
	ArrayList<ChannelItem> otherChannelList = new ArrayList<ChannelItem>();
	//标签
	private TagFlowLayout mTagListView;
	private final List<String> mTags = new ArrayList<String>();
	private final String[] titles = { "内科", "外科", "妇产科", "儿科", "肿瘤", "营养科",
			"耳鼻喉", "眼科", "口腔科", "中医", "保健", "骨科", "男科", "皮肤科", "心理科", "跑步" };
	//最终选择的标签位置
	Set<Integer> selectedPosSet=new HashSet<Integer>();
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);	
		intiateView();
	}
	private void setUpData() {
		for (int i = 0; i < 16; i++) {
			mTags.add(titles[i]);
		}
	}
	
	private void intiateView(){
		bt_back=(Button)findViewById(R.id.back);
		et_username=(EditText)findViewById(R.id.et_username);
		et_password=(EditText)findViewById(R.id.et_password);
		et_phone=(EditText)findViewById(R.id.et_phone);
		tb_gender=(ToggleButton)findViewById(R.id.tb_gender);
		et_deviceId=(EditText)findViewById(R.id.et_device);
		et_weight=(EditText) findViewById(R.id.et_weight);
		et_height=(EditText) findViewById(R.id.et_height);
		mTagListView=(TagFlowLayout) findViewById(R.id.id_flowlayout);
		setUpData();
		mTagListView.setAdapter(new TagAdapter<String>(mTags) {
			@Override
		       public View getView(FlowLayout parent, int position, String s)
		       {
				LayoutInflater myinflater=LayoutInflater.from(getApplicationContext());
		           TextView tv = (TextView) myinflater.inflate(R.layout.tag,mTagListView, false);
		           tv.setText(s);
		           return tv;
		       }
		});
/*		mTagListView.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
			
			@Override
			public boolean onTagClick(View view, int position, FlowLayout parent) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), titles[position], Toast.LENGTH_SHORT).show();
				return true;
			}
		});*/
		mTagListView.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
			
			@Override
			public void onSelected(Set<Integer> selectPosSet) {
				// TODO Auto-generated method stub
//				Toast.makeText(getApplicationContext(), selectPosSet.toString(), Toast.LENGTH_SHORT).show();
				selectedPosSet=selectPosSet;
			}
		});
		
		bt_register=(Button)findViewById(R.id.bt_register);
		
		bt_back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				RegisterActivity.this.finish();
			}
		});
		bt_register.setOnClickListener(new RegisterListener());
	}
	
	class RegisterListener implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			username=et_username.getText().toString();
			password=et_password.getText().toString();
			gender=tb_gender.getText().toString();
			phone=et_phone.getText().toString();
			deviceId=et_deviceId.getText().toString();
			weight=et_weight.getText().toString();
			height=et_height.getText().toString();
			
			boolean netstate=MyUtils.isNetworkConnected(getApplicationContext());
			if(!netstate){
				Toast.makeText(RegisterActivity.this,"网络无法连接，请检查您的网络！",Toast.LENGTH_SHORT).show();
			}else if(username.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写用户名！",Toast.LENGTH_SHORT).show();
			}else if(password.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写密码！",Toast.LENGTH_SHORT).show();
			}else if(phone.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写手机号码！",Toast.LENGTH_SHORT).show();
			}else if(deviceId.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写沙发ID！",Toast.LENGTH_SHORT).show();
			}else if(weight.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写体重！",Toast.LENGTH_SHORT).show();
			}else if(height.equals("")){
				Toast.makeText(RegisterActivity.this,"请填写身高！",Toast.LENGTH_SHORT).show();
			}
			else{
				//初始化list和数据库
				ChannelManage.getManage(new SQLHelper(getApplicationContext())).deleteAllChannel();
				List<ChannelItem> otherChannelList=new ArrayList<ChannelItem>();
				otherChannelList=ChannelManage.defaultOtherChannels;
				interestTag="";//置空interestTag
				int k=0;//用来判断是否加“#”
				Set<Integer> pos_set=new TreeSet<Integer>(new MyComparator1());//升序
				for(Integer i:selectedPosSet){
					pos_set.add(i);
				}
				for(Integer i:pos_set){					
					interestTag+=titles[i];	
					k++;
					if(k<pos_set.size()){
						interestTag+="#";
					}
					ChannelManage.defaultUserChannels.add(ChannelManage.defaultOtherChannels.get(i));
					System.out.println("i值：--------"+i);				
				}
				Set<Integer> inv_set=new TreeSet<Integer>(new MyComparator2());//升序
				for(Integer i:selectedPosSet){
					inv_set.add(i);
				}
				for(int i:inv_set){
					otherChannelList.remove(i);	
				}

				//保存在SQLite数据库中			
				ChannelManage.getManage(new SQLHelper(getApplicationContext())).saveUserChannel(ChannelManage.defaultUserChannels);
				System.out.println("未选择的频道数目：-------"+otherChannelList.size());
				ChannelManage.getManage(new SQLHelper(getApplicationContext())).saveOtherChannel(otherChannelList);
				
				mDialog = new ProgressDialog(RegisterActivity.this);
				mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				mDialog.setMessage("正在处理，请稍候...");
				mDialog.show();
				Thread reg_thread=new Thread(new Register());
				reg_thread.start();
			}
		}		
	}
	//set升序排列
	class MyComparator1 implements Comparator<Integer>{  
		  
	    public int compare(Integer o1, Integer o2) {  
	          
	        return o1.compareTo(o2);//升序排列  
	    }
	}
	//set降序排列
	class MyComparator2 implements Comparator<Integer>{  
		  
	    public int compare(Integer o1, Integer o2) {  
	          
	        return o2.compareTo(o1);//降序排列  
	    }
	}
	
	class Register implements Runnable{
		@Override
		public void run() {
			// TODO Auto-generated method stub
		try {			
				url = MyUtils.getUrl() + "user_register?username=" + username
						+ "&password=" + password + "&phonenum=" + phone
						+ "&deviceId=" + deviceId + "&gender=" + gender
						+ "&weight=" + weight + "&height=" + height+"&interestTag="+interestTag;
				Log.i("url", url);
			HttpGet request = new HttpGet(url.replaceAll("#", "%23"));																
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
		    HttpClient httpClient = new DefaultHttpClient(httpParams);
            HttpResponse httpResponse = httpClient.execute(request);					       
	       	
	      if (httpResponse.getStatusLine().getStatusCode() == 200) {
	    	  Log.i("httpResponse.getStatusLine().getStatusCode():", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
	    	  network_timeout=true;
	          String jsonString = EntityUtils.toString(httpResponse.getEntity());
	          JSONObject json = new JSONObject(jsonString);
	          flag=json.getBoolean("success");
	          reg_msg=json.getString("msg");
	          Message msg = content_handler.obtainMessage();
				if(network_timeout){
					if (flag) {				
						msg.what = 1;									
					}else{
						msg.what = 2;			
					}
				}			
				else{
					msg.what = 3;						
				}
				content_handler.sendMessage(msg);
	         
	      }
	      }catch (Exception e) {
	        	 e.printStackTrace();
	         }
	
		}
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {	
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:	
			   	Toast.makeText(RegisterActivity.this,"注册成功，请登录！",Toast.LENGTH_SHORT).show();
		     	intent.setClass(RegisterActivity.this, LoginActivity.class);
		     	startActivity(intent);	
		     	break;
			case 2:
				Toast.makeText(RegisterActivity.this,reg_msg.toString(),Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(RegisterActivity.this,"网络连接超时!",Toast.LENGTH_SHORT).show();
				break;
		     }
		}
	};
}
